//
//  DlHttp.h
//
//  Created by 吴Sir on 16-05-20.
//
//

#import "DlHttp.h"

@implementation DlHttp
{
    NSString *callbackId;
}

- (void)request:(CDVInvokedUrlCommand*)command
{
    NSLog(@"----- request   ");
    callbackId = command.callbackId;
    NSArray *arguments = command.arguments;
    
    NSDictionary *args = arguments[0];
    
    NSString *url = [args objectForKey:@"url"];
    NSString *type = [args objectForKey:@"type"];
    float timeout = [[args objectForKey:@"timeout"] floatValue];
    NSString *dataType = [args objectForKey:@"dataType"];
    
    if ([@"POST" isEqualToString:type]) {
        NSDictionary *params = [args objectForKey:@"params"];
        [self postRequest:url params:params timeout:timeout completionHandler:^(NSString* result, NSError* error) {
            [self callback:dataType result:result];
        }];
    } else if ([@"GET" isEqualToString:type]) {
        [self getRequest:url timeout:timeout completionHandler:^(NSString* result, NSError* error) {
            [self callback:dataType result:result];
        }];
    }

}

- (void) callback:(NSString *) dataType result:(NSString*) result
{
    if (result) {
        if ([@"text" isEqualToString:dataType]) {
            CDVPluginResult* callback = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result];
            [self.commandDelegate sendPluginResult:callback callbackId:callbackId];
        } else {
            if ([@"jsonp" isEqualToString:dataType]) {
                result = [self jsonpToJson:result];
            }
            
            NSError *error;
            NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *dictReult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
            CDVPluginResult* callback = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictReult];
            [self.commandDelegate sendPluginResult:callback callbackId:callbackId];
        }
    } else {
        CDVPluginResult* callback = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"request failed"];
        [self.commandDelegate sendPluginResult:callback callbackId:callbackId];
    }
}

- (void) getRequest:(NSString *) url timeout:(float) timeout completionHandler:(void (^)(NSString*, NSError*))completionHandler
{
    if (timeout == 0) {
        timeout = 5.0; // 默认5秒超时
    } else {
        timeout = timeout/1000;
    }
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:timeout];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error)
         {
             completionHandler(nil, error);
             return ;
         }
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
         if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304)
         {
             NSString *result =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             completionHandler(result, error);
         }
         else
         {
             completionHandler(nil, error);
         }
     }];
}

- (void) postRequest:(NSString *) url params:(NSDictionary *) params timeout:(long) timeout completionHandler:(void (^)(NSString*, NSError*))completionHandler
{
    if (timeout == 0) {
        timeout = 5.0; // 默认5秒超时
    } else {
        timeout = timeout/1000;
    }
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:timeout];
    [request setHTTPMethod:@"POST"];
    NSString *body = [self getRequestParams:params];
    [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error)
         {
             completionHandler(nil, error);
             return ;
         }
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
         if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304)
         {
             NSString *result =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             completionHandler(result, error);
         }
         else
         {
             completionHandler(nil, error);
         }
     }];
}

- (NSString *) getRequestParams:(NSDictionary *) dict
{
    NSString *params = @"";
    NSArray *keys = [dict allKeys];
    int count = (int)[keys count];
    for (int i = 0; i < count; i++)
    {
        NSString *key = [keys objectAtIndex: i];
        id value = [dict objectForKey: key];
        NSLog (@"Key: %@ for value: %@", key, value);
        params = [NSString stringWithFormat:@"%@&%@=%@", params, key, [value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    if ([params length] > 0) {
        params = [params substringFromIndex:1];
    }
    return params;
}

- (NSString *) jsonpToJson:(NSString *) str
{
    NSRange range1 = [str rangeOfString:@"("];
    NSRange range2 = [str rangeOfString:@")" options:NSBackwardsSearch];
    if (range1.length != 0 && range2.length != 0) {
        NSRange range = NSMakeRange(range1.location+1, range2.location-range1.location-1);
        str = [str substringWithRange:range];
    }
    return str;
}


@end